<template>
  <div>
    <van-form @submit="turnToDetail">
      <CpNavBar title="通信费用理财表" />
      <div class="demo-section">
        <div class="basicInfo" style="margin-top: var(--van-nav-bar-height)">
          <div class="boxTitle">基础信息：</div>
          <van-cell-group inset>
            <!-- 输入客户姓名 -->
            <van-field
              v-model="name"
              label="客户姓名"
              input-align="right"
              placeholder="请输入"
              label-width="32vw"
            />
            <!-- 输入地址 -->
            <van-field
              v-model="area"
              label="地址"
              input-align="right"
              placeholder="请输入"
              label-width="32vw"
            />
            <!-- 输入手机号，调起手机号键盘 -->
            <van-field
              v-model="tel"
              type="tel"
              label="号码"
              input-align="right"
              placeholder="请输入"
              label-width="32vw"
              :rules="[
                { required: true, message: '请填写手机号' },
                {
                  message: '手机格式错误',
                  pattern: new RegExp(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/)
                }
              ]"
            />
          </van-cell-group>
        </div>
        <div class="basicInfo">
          <div class="boxTitle">基本套餐：</div>
          <van-cell-group inset>
            <!-- 输入流量 -->
            <van-field
              v-model="flow"
              label="流量"
              input-align="center"
              placeholder="请输入"
              type="number"
              label-width="32vw"
            >
              <template #extra>
                <div class="extra">G</div>
              </template>
            </van-field>
            <!-- 输入语音 -->
            <van-field
              v-model="voice"
              label="语音"
              input-align="center"
              placeholder="请输入"
              type="number"
              label-width="32vw"
            >
              <template #extra>
                <div class="extra">分钟</div>
              </template>
            </van-field>
            <!-- 输入宽带 -->
            <van-field
              v-model="broadband"
              label="宽带"
              input-align="center"
              placeholder="请输入"
              type="number"
              label-width="32vw"
            >
              <template #extra>
                <div class="extra">M</div>
              </template>
            </van-field>
            <!-- 输入电视 -->
            <van-field
              v-model="television"
              type="tel"
              label="电视"
              input-align="center"
              placeholder="请输入"
              label-width="32vw"
            >
              <template #extra>
                <div class="extra"></div>
              </template>
            </van-field>
            <!-- 输入实际消费 -->
            <van-field
              v-model="realConsumption"
              type="number"
              label="实际消费"
              input-align="center"
              placeholder="请输入"
              label-width="32vw"
            >
              <template #extra>
                <div class="extra">元</div>
              </template>
            </van-field>
          </van-cell-group>
        </div>
        <div class="basicInfo">
          <div class="boxTitle">其他家人：</div>
          <van-cell-group inset>
            <div v-for="(item, index) in familyRelation" :key="index">
              <van-field
                v-model="item.type"
                readonly
                input-align="center"
                :label="'家人' + (index + 1)"
                placeholder="请选择关系"
                @click="() => openFamilyPopup(index)"
                label-width="32vw"
              >
                <template #right-icon>
                  <div class="extra">
                    <img src="@/assets/downIcon.png" />
                  </div>
                </template>
              </van-field>
              <van-popup
                v-model:show="showPickerFamily"
                round
                position="bottom"
              >
                <van-picker
                  :columns="familyColumns"
                  @cancel="showPickerFamily = false"
                  @confirm="onConfirmFamily"
                >
                  <template #option="item">
                    <div v-if="item.text !== '其他'">
                      {{ item.text }}
                    </div>
                    <div
                      v-else
                      style="
                        display: flex;
                        justify-content: center;
                        align-items: center;
                      "
                    >
                      <div>{{ item.text }}，</div>
                      <div>
                        <input
                          type="text"
                          class="custom-input"
                          placeholder="请输入"
                          v-model="otherFamilyColumns"
                        />
                      </div>
                    </div>
                  </template>
                </van-picker>
              </van-popup>
              <!-- 输入地址 -->
              <van-field
                v-model="item.number"
                label="消费"
                input-align="center"
                placeholder="请输入"
                label-width="32vw"
                type="number"
              >
                <template #extra>
                  <div class="extra">元</div>
                </template>
              </van-field>
            </div>
            <!-- 添加输入框的按钮 -->
            <div class="addButtonBox">
              <el-button type="primary" text @click="addRelation"
                >添加家属消费</el-button
              >
            </div>
          </van-cell-group>
        </div>
        <div class="basicInfo">
          <div class="boxTitle">推荐套餐：</div>
          <van-radio-group v-model="checked">
            <van-cell-group inset>
              <div>
                <van-field
                  v-model="setMenuType"
                  readonly
                  input-align="center"
                  label="套餐类别"
                  placeholder="请选择套餐类别"
                  @click="showPickerSetMenu = true"
                  label-width="32vw"
                >
                  <template #right-icon>
                    <div class="extra">
                      <img src="@/assets/downIcon.png" />
                    </div>
                  </template>
                </van-field>
                <van-popup
                  v-model:show="showPickerSetMenu"
                  round
                  position="bottom"
                >
                  <van-picker
                    :columns="setMenuColumns"
                    @cancel="showPickerSetMenu = false"
                    @confirm="onConfirmSetMenu"
                  />
                </van-popup>
                <!-- 输入地址 -->
                <van-field
                  v-if="setMenuType"
                  v-model="setMenuNumber"
                  readonly
                  input-align="center"
                  label="套餐"
                  placeholder="请选择套餐"
                  @click="pickerChose"
                  label-width="32vw"
                >
                  <template #right-icon>
                    <div class="extra">
                      <img src="@/assets/downIcon.png" />
                    </div>
                  </template>
                </van-field>
                <van-popup
                  v-model:show="showPickerMenuNumber1"
                  round
                  position="bottom"
                >
                  <van-picker
                    :columns="menuNumberColumns1"
                    @cancel="showPickerMenuNumber1 = false"
                    @confirm="onConfirmMenuNumber1"
                  />
                </van-popup>
                <van-popup
                  v-model:show="showPickerMenuNumber2"
                  round
                  position="bottom"
                >
                  <van-picker
                    :columns="menuNumberColumns2"
                    @cancel="showPickerMenuNumber2 = false"
                    @confirm="onConfirmMenuNumber2"
                  />
                </van-popup>
                <!-- 输入套餐优惠 -->
                <van-field
                  v-model="discount"
                  @blur="negativeChange"
                  label="套餐优惠"
                  input-align="center"
                  placeholder="请输入"
                  type="number"
                  label-width="32vw"
                >
                  <template #extra>
                    <div class="extra">元</div>
                  </template>
                </van-field>
              </div>
            </van-cell-group>
          </van-radio-group>
        </div>
        <div class="basicInfo">
          <div class="boxTitle">其他收费：</div>
          <van-cell-group inset>
            <div>
              <!-- 输入收费 -->
              <div v-for="(item, index) in reasonForCharging" :key="index">
                <van-field
                  v-model="item.reason"
                  rows="1"
                  label="其他加包收费"
                  input-align="center"
                  autosize
                  type="textarea"
                  label-width="32vw"
                  placeholder="请输入"
                >
                  <!-- @click="() => reasonPopup(index, '收费')" -->
                  <template #extra>
                    <div class="extra"></div>
                  </template>
                </van-field>
                <van-field
                  v-model="item.number"
                  placeholder="请输入"
                  label="金额"
                  input-align="center"
                  label-width="32vw"
                >
                  <!-- @click="() => reasonPopup(index, '收费')" -->
                  <template #extra>
                    <div class="extra">元</div>
                  </template>
                </van-field>
              </div>
            </div>
            <!-- 添加输入框的按钮 -->
            <!-- <div class="addButtonBox">
            <el-button type="primary" text @click="addreasonForCharging"
              >添加收费</el-button
            >
          </div> -->
          </van-cell-group>
        </div>
        <div class="basicInfo">
          <div class="boxTitle">其他优惠：</div>
          <van-cell-group inset>
            <!-- 输入其他优惠 -->

            <div v-for="(item, index) in reasonsForSavingMoney" :key="index">
              <van-field
                v-model="item.reason"
                rows="1"
                label="其他优惠"
                input-align="center"
                autosize
                type="textarea"
                label-width="32vw"
                placeholder="请输入"
              >
                <!-- @click="() => reasonPopup(index, '其他优惠')" -->
                <template #extra>
                  <div class="extra"></div>
                </template>
              </van-field>
              <van-field
                v-if="item.reason"
                v-model="item.number"
                placeholder="请输入"
                label="金额"
                input-align="center"
                label-width="32vw"
              >
                <!-- @click="() => reasonPopup(index, '其他优惠')" -->
                <template #extra>
                  <div class="extra">元</div>
                </template>
              </van-field>
            </div>
            <!-- 添加输入框的按钮 -->
            <div class="addButtonBox">
              <el-button type="primary" text @click="addreasonsForSavingMoney"
                >添加其他优惠</el-button
              >
            </div>
          </van-cell-group>
        </div>
        <div class="basicInfo">
          <div class="boxTitle">业务员：</div>
          <van-cell-group inset>
            <van-field
              v-model="salesman"
              label="业务员"
              label-width="32vw"
              type="number"
              placeholder="请输入业务员手机号"
              :rules="[
                { required: true, message: '请填写业务员手机号' },
                {
                  message: '手机格式错误',
                  pattern: new RegExp(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/)
                }
              ]"
            />
          </van-cell-group>
        </div>
        <van-dialog
          v-model:show="showReasonPopup"
          show-cancel-button
          @confirm="confirmchargingReason"
          @cancel="cancelchargingReason"
        >
          <div class="reasonBox">
            <van-field
              v-model="chargingReason"
              rows="1"
              :label="reasonType"
              autosize
              type="textarea"
              placeholder="请输入"
            />
            <van-field
              label="金额"
              type="number"
              v-model="chargingNumber"
              placeholder="请输入"
            />
          </div>
        </van-dialog>
        <el-button
          type="primary"
          class="generateButton"
          round
          native-type="submit"
          >立即生成</el-button
        >
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import CpNavBar from '@/components/CpNavBar.vue'
import { showNotify } from 'vant'
import dayjs from 'dayjs'

const query = ref<any>(useRoute().query)
const router = useRouter()

const tel = ref<any>(
  query.value?.tel ? parseInt(query.value.tel as string) : ''
) // 手机号
const name = ref<any>(query.value?.name ? (query.value?.name as string) : '') // 用户姓名
const area = ref<any>(query.value?.area ? (query.value?.area as string) : '') // 用户地址
const flow = ref<any>(
  query.value?.flow ? parseInt(query.value?.flow as string) : ''
) // 流量
const voice = ref<any>(
  query.value?.voice ? parseInt(query.value?.voice as string) : ''
) // 语音
const broadband = ref<any>(
  query.value?.broadband ? (query.value?.broadband as string) : ''
) // 宽带
const television = ref<any>(
  query.value?.television ? (query.value?.television as string) : ''
) // 电视
const realConsumption = ref<any>(
  query.value?.realConsumption ? query.value?.realConsumption : ''
) // 实际消费
const setMenuType = ref<any>(
  query.value?.setMenuType ? parseInt(query.value?.setMenuType as string) : ''
) // 套餐类别
const setMenuNumber = ref<any>(
  query.value?.setMenuNumber ? (query.value?.setMenuNumber as string) : ''
) // 套餐
const discount = ref<any>(query.value?.discount ? query.value?.discount : 0) // 套餐优惠

const salesman = ref<any>(query.value?.salesman ? query.value?.salesman : null) // 业务员

const otherFamilyColumns = ref<any>('')

const familyRelation = ref<any[]>(
  (query.value?.familyRelation as string)
    ? JSON.parse(query.value?.familyRelation as string)
    : []
)

const reasonForCharging = ref<any>(
  query.value?.reasonForCharging
    ? JSON.parse(query.value?.reasonForCharging as string)
    : [
        {
          reason: '',
          number: 0
        }
      ]
)

const reasonsForSavingMoney = ref<any>(
  (query.value?.reasonsForSavingMoney as string)
    ? JSON.parse(query.value?.reasonsForSavingMoney as string)
    : [
        {
          reason: '',
          number: 0
        }
      ]
)

const familyColumns = [
  { text: '丈夫', value: '丈夫' },
  { text: '妻子', value: '妻子' },
  { text: '父亲', value: '父亲' },
  { text: '母亲', value: '母亲' },
  { text: '儿子', value: '儿子' },
  { text: '女儿', value: '女儿' },
  { text: '其他', value: '其他' }
]

const setMenuColumns = [
  { text: '5G套餐', value: '5G套餐' },
  { text: '三千兆', value: '三千兆' }
]

const menuNumberColumns1 = [
  { text: '129套餐', value: '129套餐' },
  { text: '169套餐', value: '169套餐' },
  { text: '199套餐', value: '199套餐' },
  { text: '239套餐', value: '239套餐' },
  { text: '299套餐', value: '299套餐' }
]

const menuNumberColumns2 = [
  { text: '229套餐', value: '229套餐' },
  { text: '299套餐', value: '299套餐' }
]

const showPickerFamily = ref<boolean>(false)
const showPickerSetMenu = ref<boolean>(false)
const showPickerMenuNumber1 = ref<boolean>(false)
const showPickerMenuNumber2 = ref<boolean>(false)
const showReasonPopup = ref<boolean>(false)
const checked = ref<any>('')

const currentFamily = ref<any>(0) // 当前家人，选择关系时用
const openFamilyPopup = (index: number) => {
  showPickerFamily.value = true
  currentFamily.value = index
}

const onConfirmFamily = ({ selectedOptions }: any) => {
  if (selectedOptions[0].value !== '其他') {
    familyRelation.value[currentFamily.value].type = selectedOptions[0].value
  } else {
    familyRelation.value[currentFamily.value].type = otherFamilyColumns.value
  }
  showPickerFamily.value = false
  otherFamilyColumns.value = ''
}

const onConfirmSetMenu = ({ selectedOptions }: any) => {
  showPickerSetMenu.value = false
  setMenuType.value = selectedOptions[0].value
}

const onConfirmMenuNumber1 = ({ selectedOptions }: any) => {
  showPickerMenuNumber1.value = false
  setMenuNumber.value = selectedOptions[0].value
}

const onConfirmMenuNumber2 = ({ selectedOptions }: any) => {
  showPickerMenuNumber2.value = false
  setMenuNumber.value = selectedOptions[0].value
}

const addRelation = () => {
  if (familyRelation.value.length < 4) {
    familyRelation.value.push({ type: '', number: 0 })
  } else {
    showNotify({ type: 'danger', message: '最多添加4位家庭成员' })
  }
}

// const addreasonForCharging = () => {
//   reasonForCharging.value.push({ reason: '', number: 0 })
// }

const addreasonsForSavingMoney = () => {
  reasonsForSavingMoney.value.push({ reason: '', number: 0 })
}

const pickerChose = () => {
  if (setMenuType.value === '5G套餐') {
    showPickerMenuNumber1.value = true
    return
  }
  if (setMenuType.value === '三千兆') {
    showPickerMenuNumber2.value = true
    return
  }
}

const reasonIndex = ref<any>(0)
const reasonType = ref<any>('')
const chargingReason = ref<any>('')
const chargingNumber = ref<any>(0)
const reasonPopup = (index: number, type: string) => {
  reasonIndex.value = index
  reasonType.value = type
  if (type === '收费') {
    chargingReason.value = reasonForCharging.value[reasonIndex.value].reason
      ? reasonForCharging.value[reasonIndex.value].reason
      : ''
    chargingNumber.value = reasonForCharging.value[reasonIndex.value].number
      ? reasonForCharging.value[reasonIndex.value].number
      : 0
  }
  if (type === '其他优惠') {
    chargingReason.value = reasonsForSavingMoney.value[reasonIndex.value].reason
      ? reasonsForSavingMoney.value[reasonIndex.value].reason
      : ''
    chargingNumber.value = reasonsForSavingMoney.value[reasonIndex.value].number
      ? reasonsForSavingMoney.value[reasonIndex.value].number
      : 0
  }
  showReasonPopup.value = true
}

const confirmchargingReason = () => {
  if (reasonType.value === '收费') {
    reasonForCharging.value[reasonIndex.value].reason = chargingReason.value
    reasonForCharging.value[reasonIndex.value].number = chargingNumber.value
  }
  if (reasonType.value === '其他优惠') {
    reasonsForSavingMoney.value[reasonIndex.value].reason = chargingReason.value
    reasonsForSavingMoney.value[reasonIndex.value].number = chargingNumber.value
  }
  showReasonPopup.value = false
  chargingReason.value = ''
  chargingNumber.value = 0
}

const cancelchargingReason = () => {
  showReasonPopup.value = false
  chargingReason.value = ''
  chargingNumber.value = 0
}

const negativeChange = (value: any) => {
  console.log(value)

  if (value) {
    discount.value = '-' + discount.value
  }
}

const getWeek = () => {
  let datas = dayjs().day()
  let week = ['日', '一', '二', '三', '四', '五', '六']
  return '星期' + week[datas]
}

const date = ref(dayjs().format('YYYY年MM月DD日') + getWeek())

const turnToDetail = () => {
  reasonForCharging.value.map((item: any) => {
    // 检查 item 是否有 reason 和 number 属性
    return item.reason !== undefined && item.number !== undefined
  })
  reasonsForSavingMoney.value.map((item: any) => {
    // 检查 item 是否有 reason 和 number 属性
    return item.reason !== undefined && item.number !== undefined
  })
  const familyRelationTemp = familyRelation.value.filter((item: any) => {
    // 检查 item 是否为空
    return !(item.type === '' && item.number === '0')
  })
  console.log(familyRelationTemp)

  const reasonForChargingTemp = reasonForCharging.value.filter((item: any) => {
    // 检查 item 是否为空
    return !(item.reason === '' && item.number === '0')
  })
  const reasonsForSavingMoneyTemp = reasonsForSavingMoney.value.filter(
    (item: any) => {
      // 检查 item 是否为空
      return !(item.reason === '' && item.number === '0')
    }
  )
  router.push({
    path: '/about',
    query: {
      date: date.value,
      tel: tel.value,
      name: name.value,
      area: area.value,
      flow: flow.value,
      voice: voice.value,
      broadband: broadband.value,
      television: television.value,
      realConsumption: realConsumption.value,
      setMenuType: setMenuType.value,
      setMenuNumber: setMenuNumber.value,
      discount: discount.value,
      familyRelation: JSON.stringify(familyRelationTemp),
      reasonForCharging: JSON.stringify(reasonForChargingTemp),
      reasonsForSavingMoney: JSON.stringify(reasonsForSavingMoneyTemp),
      salesman: salesman.value
    }
  })
}
</script>

<style scoped lang="scss">
.demo-section {
  box-sizing: border-box;
  min-height: calc(100vh - 15vw);
  padding-bottom: 20px;
  background-color: #f7f8fc;
}

.boxTitle {
  color: #666666;
  margin: var(--van-cell-group-inset-padding);
  padding: 16px 0;
}

.basicInfo {
  background-color: #f7f8fc;
}

:deep() {
  .van-field__label {
    color: #333333;
    font-weight: 600;
  }
}

.extra {
  width: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 600;
}

.addButtonBox {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px 0;
  border-top: 1px solid #ebedf0;
  background-color: #fff;
}

.addButton {
  color: #2a6bfc;
}

.generateButton {
  width: calc(100% - 8.53334vw);
  margin: 4.26667vw;
  padding: 4.26667vw 0;
  height: 12.8vw;
  border-radius: 8.53vw;
  font-size: 4.8vw;
  background-color: #2a6bfc;
}

.reasonBox {
  padding: 16px;
}

.custom-input {
  width: 72px; /* 设置输入框宽度 */
  border: none; /* 移除所有边框 */
  border-bottom: 1px solid #999; /* 只保留下边框，并设置颜色 */
  outline: none; /* 去掉聚焦时的轮廓线 */
  padding: 0; /* 移除内边距 */
  font-size: 16px; /* 设置字体大小 */
  line-height: 24px; /* 设置行高，使输入框高度合适 */
  text-align: center;
}

:deep() {
  .van-field__error-message {
    text-align: right;
  }
}
</style>
